package ch.ffhs.services;

import ch.ffhs.contacts.Contact;
import android.telephony.SmsManager;
import android.util.Log;
import android.os.AsyncTask;

/**
 * class SmsSenterTask. Implements an Async task for sending an
 * emergency-message to an emergeny contact.
 * 
 * @author mf
 * @author sw
 */
public class SmsSenderTask extends AsyncTask<String, Void, Void> {

	private Contact contact = null;
	private GpsPosition gpsPosition = null;
	private String messageBody = "";

	/**
	 * sets the contact-information for the message
	 * 
	 * @param contact
	 *            contact to which the sms has to be sent
	 */
	public void setContact(Contact contact) {
		this.contact = contact;
	}

	/**
	 * sets the gps-information for the message
	 * 
	 * @param gpsPosition
	 *            GPS information which will be included in message-body
	 */
	public void setGpsPosition(GpsPosition gpsPosition) {
		this.gpsPosition = gpsPosition;
	}

	@Override
	protected Void doInBackground(String... params) {
		if ((contact != null) && (gpsPosition != null)) {
			messageBody = params[0];
			// send sms
			sendSms(contact, gpsPosition);
		}
		return null;
	}

	/**
	 * send an sms message to an given contact
	 * 
	 * @param contact
	 *            provided contact
	 * @param gpsPosition
	 *            provided location
	 */
	public void sendSms(final Contact contact, final GpsPosition gpsPosition) {

		String smsText = createSmsText(gpsPosition);

		final SmsManager smsManager = SmsManager.getDefault();

		if (ServiceManager.testMode) {
			Log.d("SmsSenderTask", "sendSms to 0000");
			smsManager.sendTextMessage("+0000", null, smsText, null, null);
		} else {
			Log.d("SmsSenderTask", "sendSms to " + contact.toString());
			smsManager.sendTextMessage(contact.getNumberSMS(), null, smsText,
					null, null);
		}
	}

	private String createSmsText(final GpsPosition gpsPosition) {
		Log.d("SmsSenderTask", "createSmsText: " + gpsPosition.getPositionUrl());
		final StringBuilder smsTextBuilder = new StringBuilder();
		smsTextBuilder.append(messageBody);
		smsTextBuilder.append(gpsPosition.getPositionUrl());
		return smsTextBuilder.toString();
	}
}
